<template>
  <div>
    <div style="margin-bottom: 20px">
      <a-button type="primary" shape="round" size="large" ghost @click="visible = !visible">添加</a-button>
      <a-divider type="vertical" />
      <a-button type="primary" shape="round" size="large" ghost @click="refresh">刷新</a-button>
    </div>
    <!--表格-->
    <a-table
      :columns="columns"
      :rowKey="record => record.uuid"
      :dataSource="sentences"
      :pagination="pagination"
      :loading="loading"
      size="middle"
      bordered>
      <!--自定义时间-->
      <template slot="fromNow" slot-scope="text, record, index">
        <span :title="moment(record.createAt).format('YYYY-MM-DD HH:MM:ss')">{{ text }}</span>
      </template>
      <!--自定义状态-->
      <template slot="status" slot-scope="text, record, index">
        <a-icon type="check-circle" style="color: #87d068;font-size: 20px" v-if="record.status"/>
        <a-icon type="close-circle" style="color: orange;font-size: 20px" v-else/>
      </template>
      <!--自定义操作-->
      <template slot="operation" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <a-button size="small"
                    ghost
                    type="primary"
                    @click="editSentence(record)"
                    shape="round">编辑</a-button>
          <a-popconfirm :title="`确认删除 `+record.content+ ` ?`" @confirm="deleteSentence(record)">
            <a-button size="small" ghost type="danger" shape="round">删除</a-button>
          </a-popconfirm>
        </div>
      </template>

    </a-table>

    <!--添加弹出框-->
    <a-modal title="添加句子" v-model="visible" centered @cancel="handleCancel">
      <a-form :form="form">
        <a-form-item hasFeedback >
          <a-input v-decorator="['source',　{ rules: [{ required: true, message: '来源不允许为空' }] },]"
                   size="large"
                   placeholder="请输入句子来源..."/>
        </a-form-item>

        <a-form-item hasFeedback>
          <a-textarea v-decorator="[ 'newSentence', { rules: [{ required: true, message: '句子不允许为空' }] },]"
                      :rows="4"
                      placeholder="请输入您要添加的句子..."/>
        </a-form-item>

      </a-form>
      <div slot="footer">
        <a-button
          type="primary"
          shape="round"
          size="large"
          ghost
          :loading="loading"
          @click="handleSubmit">添加</a-button>
      </div>
    </a-modal>

    <!--编辑弹出框-->
    <a-modal title="编辑句子"
             v-model="editVisible"
             centered
             @ok="editHandleOk"
             @cancel="editHandleCancel">
      <a-form-item label="来源">
        <a-input v-model="editItem.source" size="large" placeholder="请输入句子来源..."/>
      </a-form-item>
      <a-form-item label="句子">
        <a-textarea v-model="editItem.content" :rows="4" placeholder="请输入您要添加的句子..."/>
      </a-form-item>
    </a-modal>
  </div>
</template>

<script>
  import app from "../../../../app"
  import moment from "moment"
  moment.locale("zh-CN");
  export default {
    name: "sentences",
    layout: "admin",
    head: ()=>({ title: `句子列表 - ${app.name}` }),
    async asyncData({$axios, store, error }) {
      let url = `${app.api}/api/${app.apiVersion}/admin/sentences/`;
      const resp = await $axios.$get(url);
      let sentences = resp.code === 200 ? resp.data : []
      sentences.forEach((item)=>{
        let time = item.createAt
        item.fromNow = moment(time).fromNow()
      })
      return { sentences }
    },
    beforeCreate() {
      this.form = this.$form.createForm(this, { name: 'sentence-add' })
    },
    data: ()=>({
      moment,
      loading: false,
      visible: false,
      editVisible: false,
      pagination: {

      },
      editItem: {
        source: "",
        content: "",
        uuid: ""
      },
      columns: [
        {
          title: 'ID',
          dataIndex: 'id',
          width: '5%',
          scopedSlots: { customRender: 'id' },
        },
        {
          title: '创建日期',
          dataIndex: 'fromNow',
          width: '8%',
          scopedSlots: { customRender: 'fromNow' },
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: '5%',
          scopedSlots: { customRender: 'status' },
        },
        {
          title: '复制数',
          dataIndex: 'copyCounts',
          width: '5%',
          scopedSlots: { customRender: 'copyCounts' },
        },
        {
          title: '来源',
          dataIndex: 'source',
          width: '8%',
          scopedSlots: { customRender: 'source' },
        },
        {
          title: '内容',
          dataIndex: 'content',
          width: '40%',
          scopedSlots: { customRender: 'content' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
    }),
    methods: {
      editSentence(record){
        this.editVisible = true
        this.editItem.uuid = record.uuid
        this.editItem.source = record.source
        this.editItem.content = record.content
      },
      handleCancel(){
        this.visible = false;
        this.loading = false;
        this.form.resetFields();
      },
      editHandleCancel(){
        this.editVisible = false;
        this.editItem.uuid = ""
        this.editItem.source = ""
        this.editItem.content = ""
        this.loading = false;
      },
      editHandleOk(e){
        this.loading = true;
        this.$axios.$put(`${app.api}/api/${app.apiVersion}/admin/sentence/`, this.editItem)
          .then((resp)=>{
            console.log(resp)
            if (resp.code === 200) {
              const index = this._data.sentences.indexOf(resp.data);
              // let time =  resp.data.createAt
              // resp.data.fromNow = moment(time).fromNow()

              this._data.sentences[index] = resp.data

              this.editHandleCancel();
              this.$message.success(resp.msg)
            }else {
              this.$message.warning(resp.msg)
            }
          }).catch((err)=>{

        })
      },
      handleSubmit(e){
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (!err){
            this.loading = true;
            this.$axios.$post(`${app.api}/api/${app.apiVersion}/admin/sentence/`, values)
              .then((resp)=>{
                if (resp.code === 200) {
                  let time =  resp.data.createAt
                  resp.data.fromNow = moment(time).fromNow()
                  this._data.sentences.push(resp.data)
                  this.handleCancel();
                  this.$message.success(resp.msg)
                }else {
                  this.$message.warning(resp.msg);
                  this.loading = false;
                }
              }).catch((err)=>{
              // TODO 前端错误处理
              this.handleCancel();
            })
          }else {
            // 数据验证失败
          }
        })
      },
      deleteSentence(record) {
        let url = `${app.api}/api/${app.apiVersion}/admin/sentence/`;
        this.$axios.$delete(url, { data: { uuid: record.uuid } })
          .then((resp)=>{
            if (resp.code === 200) {
              const index = this._data.sentences.indexOf(record);
              this._data.sentences.splice(index, 1);
              this.$message.success(resp.msg)
            }else {
              this.$message.warning(resp.msg)
            }
          }).catch((error)=>{

        })
      },
      async refresh(){
        let url = `${app.api}/api/${app.apiVersion}/admin/sentences/`;
        const resp = await this.$axios.$get(url);
        console.log(resp)
        let sentences = resp.code === 200 ? resp.data : []
        sentences.forEach((item)=>{
          let time = item.createAt
          item.fromNow = moment(time).fromNow()
        })
        this._data.sentences = sentences
      }
    }
  }
</script>

<style scoped>

</style>
